<?php
/*******************************************
	Security procedures
*******************************************/

// Avoid direct access
if(substr_count($_SERVER['PHP_SELF'], 'security.php') > 0) {
	header("HTTP/1.0 404 Not Found");
	exit;
}


class Security {

	protected static $protected_pages = array("profile", "saved-searches", "edit-saved-search", "submit-related-item");

	// PROTECTED PAGES PERMISSIONS VERIFICATION
	public static function verify_page_permissions($page) {

		for($i=0; $i<count(self::$protected_pages); $i++) {
			if( $page == self::$protected_pages[$i] ) {
				// the page require permissions
				return true;
			}
		}
		
		// the page doesn't require permissions
		return false;
	}
	
	// USER'S IP
	public static function get_user_ip() {
	
		$ip = "";
	
		if(getenv('HTTP_CLIENT_IP')) {
			$ip = getenv('HTTP_CLIENT_IP');
		} else if(getenv('HTTP_X_FORWARDED_FOR')) {
		  	$ip = getenv('HTTP_X_FORWARDED_FOR');
		} else {
			$ip = getenv('REMOTE_ADDR');
		}
	
		return $ip;
	
	}
	
	// cryp/decrypt functions
	public static function crypt_string($data) {
	
		$key = CRYPT_KEY;
	
		if(strlen($key)<32) $key = md5($key);
		$ld  = strlen($data);
		$lk  = strlen($key);
		for($i=0, $crdata=""; $i<$ld; $i++)
		{
			$crdata .= sprintf("%02X",(ord($data[$i]))^(ord($key[$i%$lk])));
		}
			
		unset($ld,$lk);	
			
		return $crdata;	
	
	}
	public static function decrypt_string($cdata) {
	
		$key = CRYPT_KEY;
	
		if(strlen($key)<32) $key = md5($key);
		$ld  = strlen($cdata);
		$lk  = strlen($key);
		for($i=0, $data=""; $i<$ld; $i+=2)
		{
			$data .= chr((hexdec(substr($cdata, $i, 2)))^(ord($key[($i>>1)%$lk])));
		}
	
		unset($ld,$lk);	
	
		return $data;
	
	}

}

?>